package com.ruoyi.kubernetes.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.X0017_StrongEncryptionHeader;
import org.apache.poi.poifs.crypt.dsig.CertificateSecurityException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
import org.bouncycastle.util.encoders.Base64;
import com.ruoyi.kubernetes.models.*;

import javax.security.auth.x500.X500Principal;
import java.nio.charset.StandardCharsets;
import java.security.*;

@Slf4j
public class KRsaUtils {
    private static final int KEY_SIZE = 2048;

    private static final String Algorithm = "RSA";

    private static final String CSR_MODE = "SHA256withRSA";

    private static final Provider BC = new BouncyCastleProvider();

    public static ClientCSRData generateRSAKeyPair(String cn,String o) {
        ClientCSRData result = new ClientCSRData();
        try {
            KeyPairGenerator gen = KeyPairGenerator.getInstance(Algorithm, BC);
            gen.initialize(KEY_SIZE);
            KeyPair pair = gen.generateKeyPair();
            PrivateKey privateKey = pair.getPrivate();
            PublicKey publicKey = pair.getPublic();
            String subjectStr = "CN="+cn;
            if (o!=null){
                subjectStr+=",O="+o;
            }
            X500Principal subject = new X500Principal(subjectStr);
            ContentSigner signGen = new JcaContentSignerBuilder("SHA256withRSA").build(privateKey);
            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject, publicKey);
            PKCS10CertificationRequest csr = builder.build(signGen);
            String csrStr = new String(Base64.encode(csr.getEncoded()));
            String csrCode = "-----BEGIN CERTIFICATE REQUEST-----\n";
            csrCode += csrStr;
            csrCode += "\n-----END CERTIFICATE REQUEST-----\n";
            String privateKeyCode = "-----BEGIN RSA PRIVATE KEY-----\n";
            privateKeyCode += new String(Base64.encode(privateKey.getEncoded()));
            privateKeyCode += "\n-----END RSA PRIVATE KEY-----\n";
            result.setClient_publicKey(Base64.toBase64String( Base64.encode(publicKey.getEncoded())));
            result.setClient_privateKey(Base64.toBase64String(privateKeyCode.getBytes(StandardCharsets.UTF_8)));
            result.setClient_csr(Base64.toBase64String(csrCode.getBytes(StandardCharsets.UTF_8)));
        }catch (Exception exception){
            log.error(exception.getMessage());
            throw new CertificateSecurityException();
        }
        return result;
    }
}
